package crmdna.api.servlet;

import java.io.IOException;
import java.net.URLDecoder;

import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.servlet.auth.oauth2.AbstractAuthorizationCodeCallbackServlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import crmdna.api.servlet.Utils;

public class GoogleOAuth2CallbackServlet extends
		AbstractAuthorizationCodeCallbackServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void onSuccess(HttpServletRequest req, HttpServletResponse resp,
			Credential credential) throws ServletException, IOException {
		String state = URLDecoder.decode(req.getParameter("state"), "UTF-8");
		String[] params = state.split("\\|");
		
		HttpSession sess = req.getSession(true);
		sess.setAttribute("login", params[0]);
		sess.setAttribute("loginType", "google");

		resp.sendRedirect(params[1]);
	}

	@Override
	protected void onError(HttpServletRequest req, HttpServletResponse resp,
			AuthorizationCodeResponseUrl errorResponse)
			throws ServletException, IOException {
		String state = URLDecoder.decode(req.getParameter("state"), "UTF-8");
		String[] params = state.split("\\|");
		resp.sendRedirect(params[2]);
	}

	@Override
	protected String getRedirectUri(HttpServletRequest req)
			throws ServletException, IOException {
		return Utils.getRedirectUri(req);
	}

	@Override
	protected AuthorizationCodeFlow initializeFlow() throws IOException {
		return Utils.newFlow();
	}

	@Override
	protected String getUserId(HttpServletRequest arg0)
			throws ServletException, IOException {
		
		String state = URLDecoder.decode(arg0.getParameter("state"), "UTF-8");
		String[] params = state.split("\\|");
		return params[0];
	}
}